import React, { Component } from "react";
import LogoImg from "images/logo.png";
import { messages } from "share/common";
import moment from "moment";
import UpdateRenewal from "components/template/dingding/update-renewal";
import { Modal, Progress, Icon, Popover, Button } from "antd";
import TweenOne from "rc-tween-one";
import Children from "rc-tween-one/lib/plugin/ChildrenPlugin";
import debounce from "lodash.debounce";

TweenOne.plugins.push(Children);

const showMap = [
  {
    key: "activityCount",
    name: messages("basic-1.key255") /*已激活*/,
    animationName: "animationActive",
    firstKey: "activityCount",
    compareKey: "licensedCount",
    className: "green-bar",
    showProgress: true,
  },
  {
    key: "licensedCount",
    name: messages("basic-1.key164") /*已购买*/,
    animationName: "animationBuy",
    firstKey: "licensedCount",
    compareKey: "totalCount",
    className: "blue-bar",
    showProgress: true,
  },
  {
    key: "totalCount",
    name: messages("basic-1.key256") /*员工总数*/,
    animationName: "animationTotalEmployee",
    showProgress: false,
  },
];

class ShowInfo extends Component {
  constructor(props) {
    super(props);
    this.state = {
      cardData: props.cardData,
      renewVisible: false,
      animationActive: null,
      animationBuy: null,
      animationTotalEmployee: null,
    };
    this.compareData = debounce(this.compareData, 300);
    this.flag = false;
  }

  componentDidMount() {
    this.compareData(this.props.cardData);
  }

  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.cardData && nextProps.cardData.totalCount && !this.flag) {
      this.compareData(nextProps.cardData);
      this.flag = true;
    }
  }

  compareData = (nextCardData) => {
    const { cardData } = this.state;
    showMap.map((item) => {
      if (cardData[item.key] !== nextCardData[item.key]) {
        this.trigger(nextCardData[item.key], item.animationName);
      }
    });
  };

  validDate = () => {
    const { tenant } = this.props;
    const content = messages("basic-1.key9", {
      arg1: tenant.trialExpiredDate ? tenant.trialRemainDays || " - " : messages("dashboard.key263") /*无期限*/,
    }); /*购买的服务剩余{arg1}天，请联系客服*/
    Modal.warning({
      title: <div dangerouslySetInnerHTML={{ __html: content }} />,
      content: "400 829 7878",
    });
  };

  invalidDate = () => {
    Modal.warning({
      title: messages("basic-1.key10") /*购买的服务已到期，请联系客服*/,
      content: "400 829 7878",
    });
  };

  goPurchaseHistory = () => {
    this.context.router.push("/main/purchase-history");
  };

  trigger = (value, animationName) => {
    const obj = {};
    obj[animationName] = {
      Children: {
        value: typeof value === "number" ? value : 0,
        floatLength: 0,
        formatMoney: true,
      },
      duration: 1000,
    };
    this.setState(obj);
  };

  renderContent = (tenant) => {
    return (
      <div>
        <div className="trial-date">
          {messages("basic-1.key52") /*到期时间：*/}
          {tenant.trialExpiredDate ? moment(tenant.trialExpiredDate).format("YYYY-MM-DD") : "-"}
        </div>
        <div className="btn-box">
          <Button onClick={this.goPurchaseHistory}>{messages("basic-1.key54") /*购买记录*/}</Button>
          <Button
            onClick={() => {
              this.setState({ renewVisible: true });
            }}
            type={"primary"}
          >
            {messages("basic-1.key53") /*续费*/}
          </Button>
        </div>
      </div>
    );
  };

  render() {
    const { isDingTalkEnv, tenant, cardData } = this.props;
    const { renewVisible } = this.state;

    return (
      <div className="tenant-info-box-wrapper">
        <div className={"tenant-info-box"}>
          <div className={"main-info"}>
            <div className="img-wrap">
              {tenant.logoURL ? <img className="img" src={tenant.logoURL} /> : <img className="img" src={LogoImg} />}
            </div>
            <div className="company-content">
              <div className="company-line">
                <div className="home-company-name">{tenant.tenantName}</div>
                {tenant.resourceLayout === "T" && (
                  <span>
                    {tenant.licenseType === "TRIAL" && (
                      <span className="new-trial-info">{messages("basic-1.key77") /*试用中*/}</span>
                    )}
                    {tenant.licenseType === "TEST" && (
                      <span className="new-test-info">{messages("basic-1.key78") /*内部测试*/}</span>
                    )}
                  </span>
                )}
              </div>
              <div className="company-detail">
                <span className="create-time">
                  {tenant.createdDate
                    ? `${messages("basic-1.key43") /*创建时间*/}: ${new Date(tenant.createdDate).format("yyyy-MM-dd")}`
                    : null}
                </span>
                {!isDingTalkEnv && tenant.licenseType === "TRIAL" && tenant.expireControlMode === "1" && (
                  <span className="remain-box">
                    <div className={`round-indicator ${tenant.status === "TRIAL_EXPIRED" ? "red" : "green"}`} />
                    <span className="content">
                      {tenant.status === "TRAIL" && (
                        <span className="company-probation company-probation-valid" onClick={this.validDate}>
                          {
                            tenant.trialExpiredDate
                              ? messages("basic-1.key44", {
                                  arg1: tenant.trialRemainDays || " - ",
                                }) /*剩余试用期{arg1}天*/
                              : messages("basic-1.key45") /*使用无期限*/
                          }
                        </span>
                      )}
                      {tenant.status === "TRIAL_EXPIRED" && (
                        <span className="company-probation company-probation-invalid" onClick={this.invalidDate}>
                          {messages("basic-1.key46") /*试用期已到期*/}
                        </span>
                      )}
                    </span>
                    <Icon type="ellipsis" />
                  </span>
                )}
                {isDingTalkEnv && tenant.licenseType !== "TEST" && tenant.showMaturityDate && (
                  <Popover
                    placement="bottom"
                    content={this.renderContent(tenant)}
                    getPopupContainer={(triggerNode) => triggerNode.parentNode}
                  >
                    <span className="remain-box">
                      <div
                        className={`round-indicator ${
                          tenant.status === "TRIAL_EXPIRED" ||
                          (tenant.licenseType === "REAL" && !tenant.trialExpiredDate)
                            ? "red"
                            : "green"
                        }`}
                      />
                      <span className="content">
                        {tenant.licenseType === "REAL" ? (
                          tenant.trialExpiredDate ? (
                            <span>
                              <span className="trial-block company-probation-valid" />
                              <span className="">
                                {messages("basic-1.key49") /*剩余有效期*/}&nbsp;
                                {tenant.trialRemainDays || " - "}
                                {messages("basic-1.key50") /*天*/}
                              </span>
                            </span>
                          ) : (
                            <span>
                              <span className=" trial-block company-probation-invalid" />
                              <span className="">{messages("basic-1.key51") /*服务已到期*/}</span>
                            </span>
                          )
                        ) : tenant.status === "TRAIL" ? (
                          <span>
                            <span className=" trial-block company-probation-valid" />
                            <span className="">
                              {
                                tenant.trialExpiredDate
                                  ? messages("basic-1.key44", {
                                      arg1: tenant.trialRemainDays || " - ",
                                    }) /*剩余试用期{arg1}天*/
                                  : messages("basic-1.key45") /*使用无期限*/
                              }
                            </span>
                          </span>
                        ) : (
                          tenant.status === "TRIAL_EXPIRED" && (
                            <span>
                              <span className=" trial-block company-probation-invalid" />
                              <span className="">{messages("basic-1.key51") /*服务已到期*/}</span>
                            </span>
                          )
                        )}
                      </span>
                      <Icon type="ellipsis" />
                    </span>
                  </Popover>
                )}
              </div>
            </div>
          </div>
          <div className="tenant-index-box">
            <div className="index-box">
              {showMap.map((item) => {
                return (
                  <div className={`single-index ${item.className}`}>
                    <TweenOne animation={this.state[item.animationName]} className="number">
                      0
                    </TweenOne>
                    <div className="index-name">{item.name}</div>
                    {item.showProgress && (
                      <div>
                        <Progress
                          strokeWidth={4}
                          status={"active"}
                          percent={
                            cardData[item.firstKey]
                              ? (cardData[item.firstKey] / cardData[item.compareKey]) * 100 > 100
                                ? 100
                                : (cardData[item.firstKey] / cardData[item.compareKey]) * 100
                              : 0
                          }
                          showInfo={false}
                        />
                        <div className="ratio-text">
                          {cardData[item.firstKey] || "0"}/{cardData[item.compareKey] || "0"}
                        </div>
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          </div>
        </div>
        {renewVisible && (
          <UpdateRenewal
            visible={renewVisible}
            onClose={() => {
              this.setState({ renewVisible: false });
            }}
          />
        )}
      </div>
    );
  }
}

ShowInfo.propTypes = {};

ShowInfo.contextTypes = {
  router: React.PropTypes.object,
};

export default ShowInfo;
